package com.myhealth.hb.measurmentscanner;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

import java.io.IOException;

/**
 * Created by Stephan E G Veenstra on 1-10-2014.
 */
public class AcceptThread extends Thread {
    private final BluetoothServerSocket mmServerSocket;

    private final BluetoothAdapter adapter;
    private final Main activity;

    public AcceptThread(BluetoothAdapter adapter, Main activity) {
        // Use a temporary object that is later assigned to mmServerSocket,
        // because mmServerSocket is final
        BluetoothServerSocket tmp = null;
        this.adapter = adapter;
        this.activity = activity;
        try {
            // MY_UUID is the app's UUID string, also used by the client code
            tmp = adapter.listenUsingRfcommWithServiceRecord(DeviceApplication._NAME, DeviceApplication._UUID);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.w("ADAPTER", adapter.toString());
        mmServerSocket = tmp;
    }

    public void run() {
        BluetoothSocket socket = null;
        // Keep listening until exception occurs or a socket is returned
        while (true) {
            try {
                Log.w("CONNECTOR", "Trying to connect!");
                socket = mmServerSocket.accept();
                Log.w("CONNECTOR", "Connected!");
                if (socket != null) {
                    // Do work to manage the connection (in a separate thread)


                    DeviceApplication.socket = socket;
                    activity.onConnect();
                    mmServerSocket.close();
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
            // If a connection was accepted

        }
    }

    /** Will cancel the listening socket, and cause the thread to finish */
    public void cancel() {
        try {
            mmServerSocket.close();
        } catch (IOException e) { }
    }
}
